#!/bin/bash

if [ -z "$1" ] || [ ! -e "$1" ] || [ -z "$2" ] || [ ! -e "$2" ]; then
    echo "Usages: $0 <android_sdk_dir> <iflyime_apk_file>";
    exit 0;
fi

working_dir=`pwd`

# 移除可能存在的冲突文件
rm -rf $working_dir/android_remove_latinime.patch
rm -rf $working_dir/android_default_ime_iflyime.patch

# 移除AOSP输入法
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/SYSTEM/AndroidDefaultIMEiFlyIME/android_remove_latinime.patch -o $working_dir/android_remove_latinime.patch
patch -p1 -N -d $1/build/make < $working_dir/android_remove_latinime.patch
rm -rf $working_dir/android_remove_latinime.patch

# 配置默认输入法为讯飞
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/SYSTEM/AndroidDefaultIMEiFlyIME/android_default_ime_iflyime.patch -o $working_dir/android_default_ime_iflyime.patch
patch -p1 -N -d $1/frameworks/base < $working_dir/android_default_ime_iflyime.patch
rm -rf $working_dir/android_default_ime_iflyime.patch

# 将APK写入/system/app
ime_dir=$1"/vendor/rockchip/common/apps/iFlyIME"
temp_dir=$working_dir"/temp"
mkdir -p $temp_dir
rm -rf $ime_dir
mkdir -p $ime_dir/lib/arm64
cp -f $2 $ime_dir/iFlyIME.apk
unzip -q $2 -d $temp_dir
cp -rf $temp_dir/lib/arm64-v8a/*.so $ime_dir/lib/arm64/
rm -rf $temp_dir
cat > $ime_dir/Android.mk << EOF
LOCAL_PATH := \$(my-dir)

include \$(CLEAR_VARS)
LOCAL_MODULE := iFlyIME
LOCAL_MODULE_CLASS := APPS
LOCAL_MODULE_PATH := \$(TARGET_OUT_ODM)/bundled_persist-app
LOCAL_SRC_FILES := \$(LOCAL_MODULE)\$(COMMON_ANDROID_PACKAGE_SUFFIX)
LOCAL_CERTIFICATE := PRESIGNED
#LOCAL_DEX_PREOPT := false
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE_SUFFIX := \$(COMMON_ANDROID_PACKAGE_SUFFIX)
LOCAL_JNI_SHARED_LIBRARIES_ABI := arm64
MY_LOCAL_PREBUILT_JNI_LIBS := \\
EOF

cd $ime_dir
for file in lib/arm64/*.so; do
    if [ -f "$file" ]; then
        echo "	$file\\" >> Android.mk
    fi
done
cd $working_dir

cat >> $ime_dir/Android.mk << EOF

MY_APP_LIB_PATH := \$(TARGET_OUT_ODM)/bundled_persist-app/\$(LOCAL_MODULE)/lib/\$(LOCAL_JNI_SHARED_LIBRARIES_ABI)
ifneq (\$(LOCAL_JNI_SHARED_LIBRARIES_ABI), None)
\$(warning MY_APP_LIB_PATH=\$(MY_APP_LIB_PATH))
LOCAL_POST_INSTALL_CMD :=     mkdir -p \$(MY_APP_LIB_PATH)     \$(foreach lib, \$(MY_LOCAL_PREBUILT_JNI_LIBS), ; cp -f \$(LOCAL_PATH)/\$(lib) \$(MY_APP_LIB_PATH)/\$(notdir \$(lib)))
endif
include \$(BUILD_PREBUILT)

EOF

echo "PRODUCT_PACKAGES += iFlyIME" >> $1/vendor/rockchip/common/apps/apps.mk